package cn.heygod.graywhale.runtime.task;

import cn.heygod.graywhale.runtime.context.Input;
import cn.heygod.graywhale.runtime.context.Output;
import cn.heygod.graywhale.runtime.task.def.TaskFlowDef;
import cn.heygod.graywhale.runtime.task.def.TaskNodeDef;
import cn.hutool.core.util.IdUtil;
import org.apache.poi.ss.formula.functions.T;

import java.util.ArrayList;
import java.util.List;

/**
 * 运行实例
 * @className: TaskFlow
 * @author: Simon
 * @description: TODO
 * @date: 2023/11/26 2:24
 * @version: 1.0
 */
public class TaskFlow {

    private TaskFlowDef def;

    private String flowId;

    private FlowStatus flowStatus;

    /**
     * 已经发生的节点实例
     */
    private List<TaskNode> nodes = new ArrayList<>();


    public Output start(Input input){
        //TODO 状态为STARTING
        this.flowStatus = FlowStatus.STARTING;

        Input nodeInput = input;
        Output output = null;
        for (TaskNodeDef nodeDef : def.getNodes()) {
            //创建节点实例
            TaskNode node = createNode(nodeDef);
            nodes.add(node);

            output = node.run(nodeInput);
            nodeInput = output.toInput();
        }
        return output;
    }

    private TaskNode createNode(TaskNodeDef nodeDef){
        TaskNode node = new TaskNode();
        node.setNodeId(IdUtil.getSnowflakeNextIdStr());
        node.setNodeDefId(nodeDef.getId());
        node.setTaskName(nodeDef.getTaskName());
        node.setType(nodeDef.getExecutorType());
        node.setExecutor(nodeDef.getExecutorId());
        node.setNodeStatus(TaskNode.NodeStatus.READY);
        return node;
    }


    public TaskFlowDef getDef() {
        return def;
    }

    public void setDef(TaskFlowDef def) {
        this.def = def;
    }

    public String getFlowId() {
        return flowId;
    }

    public void setFlowId(String flowId) {
        this.flowId = flowId;
    }

    public FlowStatus getFlowStatus() {
        return flowStatus;
    }

    public void setFlowStatus(FlowStatus flowStatus) {
        this.flowStatus = flowStatus;
    }

    public void addNode(TaskNode node){
        nodes.add(node);
    }

    public List<TaskNode> getNodes() {
        return nodes;
    }

    public void setNodes(List<TaskNode> nodes) {
        this.nodes = nodes;
    }

    public static enum FlowStatus{
        NEW,
        STARTING,
        RUNNING,
        STOPPING,
        STOPPED,
        FINISH

    }
}
